import { onMounted, onUnmounted, ref } from "vue";

export function useContextMenu(containerRef: any) {
  const x = ref(0);
  const y = ref(0);
  const showMenu = ref(false);
  const div = containerRef.value;

  const handleContextMenu = (e: MouseEvent) => {
    // 阻止默认的右键菜单
    e.preventDefault();
    // 阻止冒泡事件
    e.stopPropagation();
    x.value = e.clientX;
    y.value = e.clientY;
    showMenu.value = true;
  };

  function hideMenu() {
    showMenu.value = false;
  }

  // 组件加载钩子事件
  onMounted(() => {
    // 鼠标右击事件
    div?.addEventListener("contextmenu", handleContextMenu);
    // 监听点击事件，点击时隐藏菜单，捕获阶段；
    window.addEventListener("click", hideMenu, true);
    // 监听右击事件，点击时时隐藏菜单，捕获阶段；
    window.addEventListener("contextmenu", hideMenu, true);
  });

  // 组件卸载钩子事件
  onUnmounted(() => {
    // 移除事件监听
    div?.removeEventListener("contextmenu", handleContextMenu);
    window.removeEventListener("click", hideMenu, true);
    window.removeEventListener("contextmenu", hideMenu, true);
  });

  return { showMenu, x, y };
}
